#ifndef __HERM_FRAMEWORK_LISTENER_H__
#define __HERM_FRAMEWORK_LISTENER_H__

#include "herm/base/utils/log.h"
#include "herm/base/network/interface.h"

namespace herm{

class HERM_API ListenerBase : public IListener
{
public:
    ListenerBase();
	void SetPeer(IPeer* peer);
    virtual void Close(ISession* session);
private:
    virtual void Accept(ISession* session);
	virtual void PeerError(int stateType, int stateCode);
	virtual void SessionError(ISession* session, int stateType, int stateCode);
protected:
	IPeer* m_peer;
};

template <class Handler>
class HERM_API Listener : public ListenerBase
{
public:
	Handler* GetHandler(int sessionIdx)
	{
		ISession* session = m_peer->GetSession(sessionIdx);
		if (!session)
		{
			HERM_WARN("Session(idx=%d) is invalid.", sessionIdx);
			return nullptr;
		}

		IMsgHandler* handler = session->GetHandler();
		if (!handler)
		{
			HERM_WARN("Handler(%d) alreadly unregistered.", sessionIdx);
			return nullptr;
		}

		return (Handler*)handler;
	}

private:
	virtual void Accept(ISession* session)
	{
		HERM_INFO("Client connected, session idx=%d.", session->GetIndex());
		Handler* handler = CreateHandler(session);
		session->RegisterHandler(handler);
	}

	virtual Handler* CreateHandler(ISession* session) { (void)session; return nullptr; }
};
}

#endif
